import "./style/index.scss";
import { Input, Button, Table, message } from "antd";
import { getUserInfo, getUserList } from "@/api/user";
import { useState, useEffect } from "react";

const UserList = () => {
  const columns = [
    {
      title: "ID",
      dataIndex: "uid",
      key: "uid",
    },
    {
      title: "昵称",
      dataIndex: "userName",
      key: "userName",
    },
    {
      title: "权限",
      dataIndex: "userRole",
      key: "userRole",
    },
  ];
  const [data, setData] = useState([]);
  const [total, setTotal] = useState(0);
  const [messageApi, msgs] = message.useMessage();
  useEffect(() => {
    getUserInfoList(1);
  }, []);
  const [userName, setUserName] = useState("");
  const goSearchUser = () => {
    if (userName.trim() === "") {
      messageApi.error("请输入昵称");
      return;
    }
    getUserInfo({
      userName: userName,
    }).then((res) => {
      if (res.code === 200) {
        setTotal(1);
        let newArr = [{ ...res.data.user }];
        newArr.forEach((e) => {
          e.key = e.uid;
        });
        setData(newArr);
      } else {
        messageApi.error(res.message);
      }
    });
  };
  const getUserInfoList = (page) => {
    getUserList({
      page: page,
      pageSize: 10,
    }).then((res) => {
      if (res.code === 200) {
        setTotal(res.data.pageParams.total);
        let newArr = res.data.userList;
        newArr.forEach((e) => {
          e.key = e.uid;
        });
        setData(newArr);
      }
    });
  };
  const pageChange = (page) => {
    getUserInfoList(page);
  };
  const goReset = () => {
    setUserName("");
    getUserInfoList(1);
  };
  return (
    <div>
      {msgs}
      <div className="search">
        <Input
          placeholder="请输入昵称"
          value={userName}
          onChange={(e) => setUserName(e.target.value)}
        />
        <Button type="primary" onClick={goSearchUser}>
          查询用户
        </Button>
        <Button onClick={goReset}>重置</Button>
      </div>
      <div>
        <Table
          columns={columns}
          dataSource={data}
          bordered
          pagination={{ pageSize: 10, total: total, onChange: pageChange }}
        />
      </div>
    </div>
  );
};

export default UserList;
